//
//  PAChargeMoneyViewController.m
//  PAMobileWallet
//
//  Created by Pay_SMP002 on 13-7-4.
//  Copyright (c) 2013年 平安付. All rights reserved.
//

#import "PAChargeMoneyViewController.h"
#import "Global.h"
#import "PAChargeMoneyView.h"
#import "PANavView.h"
#import "PAPersonalViewController.h"
#import "PABaseViewController.h"
#import "PASecleteCardViewController.h"
#import "UIColor+Extend.h"

#import "PADataCenter.h"
#import "PANetworkManager.h"
#import "PABankCardInfo.h"
#import "PAAddCardViewController.h"

@interface PAChargeMoneyViewController ()

@end

@implementation PAChargeMoneyViewController
@synthesize selectedBankCardInfo                = _selectedBankCardInfo;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self)
    {
        chargeMoneyView = [[PAChargeMoneyView alloc] initWithFrame:RECT_PHONE];
        chargeMoneyView.parentController = self;
        self.view = chargeMoneyView;

        navView = [[PANavView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, 44)];
        navView.delegate = self;
        [navView setTitle:@""];
        [chargeMoneyView addSubview:navView];
        
        controllerT = nil;
        if (!addCardViewController) {
            addCardViewController = [[PAAddCardViewController alloc] initWithNibName:nil bundle:nil];
            addCardViewController.parentController = self;
        }
        controllerT = addCardViewController;

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(selectedBankCard:) name:NOT_SelectedCard object:nil];
    }
    return self;
}

#pragma mark - PANavViewDelegate methods

- (void)sendSelf:(PANavView *)sendView
{
    [navView setTitle:@""];
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)testNext:(id)sender
{
    int tag = [(UIButton *)sender tag];
    PABaseViewController * controller = nil;

    if (tag == 10)  // 去选择卡的界面
    {
        if (!secleteCardViewController)
        {
            secleteCardViewController = [[PASecleteCardViewController alloc] initWithNibName:nil bundle:nil];
            secleteCardViewController.parentController = self;
        }
        controller = secleteCardViewController;
        [secleteCardViewController sendNavTitle:getMarkType];
        [self.navigationController pushViewController:controller animated:YES];
    }
    
    if (tag == 20) // 回到个人中心
    {
        chargeMoneyView.confirmButton.enabled = NO;
        [chargeMoneyView.confirmButton setBackgroundImage:[UIImage imageNamed:@"button_B1.png"] forState:UIControlStateNormal];
        [chargeMoneyView.confirmButton setTitleColor:ENABLE_COLOR forState:UIControlStateNormal];
        
        NSString * dateStr = [NSString stringWithFormat:@"%g" ,[[NSDate date] timeIntervalSince1970]];
        if ([getMarkType isEqualToString:@"充值"]){
            NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_recharge",k_bankCardId:[NSNumber numberWithLongLong:[getBankCardID longLongValue]],k_rechargeAmount:[NSNumber numberWithDouble:[chargeMoneyView.moneyText.text doubleValue]],k_payPassword:chargeMoneyView.payPwdText.text,k_clientPaymentId:[NSString stringWithFormat:@"%@-%@",getBankCardID,dateStr]}];
            [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
            
        }
        else if ([getMarkType isEqualToString:@"提现"]){
            NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_withdraw",k_bankCardId:[NSNumber numberWithLongLong:[getBankCardID longLongValue]],k_withdrawAmount:[NSNumber numberWithDouble:[chargeMoneyView.moneyText.text doubleValue]],k_payPassword:chargeMoneyView.payPwdText.text,k_clientPaymentId:[NSString stringWithFormat:@"%@-%@",getBankCardID,dateStr]}];
            [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:self];
        }
    }
}

- (void)paRequestRespons:(NSDictionary *)responsDic userInfo:(NSDictionary *)userInfo
{
    NSString * op = [responsDic objectForKey:k_operationType];
    NSString * messageStr;
    if ([op isEqualToString:@"op_recharge"]){
        
        messageStr = [NSString stringWithFormat:@"恭喜您！已经成功充值%@元",chargeMoneyView.moneyText.text];
        NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_query_balance"}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:nil];
    }
    else if ([op isEqualToString:@"op_withdraw"])
    {
        messageStr = [NSString stringWithFormat:@"您已成功申请提现,请在1-2个工作日查询(%@)",chargeMoneyView.cardNumLable.text];
        NSMutableDictionary *postingDic = [[NSMutableDictionary alloc] initWithDictionary:@{k_operationType:@"op_query_balance"}];
        [[PANetworkManager sharedInstance] reqAsynParamDic:postingDic userInfo:nil delegate:nil];
    }
    
    UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:messageStr delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
    alert.tag = 10;
    [alert show];
    
    chargeMoneyView.confirmButton.userInteractionEnabled = YES;
}
- (void)paRequestAccurateFailed:(NSInteger)errorCode userInfo:(NSDictionary *)userInfo
{
    chargeMoneyView.confirmButton.userInteractionEnabled = YES;
}
- (void)paRequestTimeout:(NSDictionary *)userInfo
{
    chargeMoneyView.confirmButton.userInteractionEnabled = YES;
}
- (void)sendNavTitle:(NSString *)navTitleStr;
{
    if (navTitleStr)
    {
        [navView setTitle:navTitleStr];
        getMarkType = navTitleStr;
    }
}
- (void)loadSelecteBankCardInfo
{
    cardMarkArray = [BANKCARD_MARK componentsSeparatedByString:@","]; //本地银行名字（简写）
    getBankCardID = self.selectedBankCardInfo.bankCardId;  //银行卡id  （卡的唯一标识）
    cardMarkStr = self.selectedBankCardInfo.bankMark;      //对应某个银行的名字简写
    
    if (self.selectedBankCardInfo.bankCardType == BCT_DEBIT_CARD)
    {
        bankCardTypeStr = @"信用卡";
    }
    
    if (self.selectedBankCardInfo.bankCardType == BCT_CREDIT_CARD)
    {
        bankCardTypeStr = @"借记卡";
    }
    
    NSLog(@"====== %@ \n ====%@ ",self.selectedBankCardInfo.bankCardNum,bankCardTypeStr);
    
    for (int i = 0; i < [cardMarkArray count]; i++)
    {
        NSString * cardMarkString = [cardMarkArray objectAtIndex:i];
        if ([cardMarkStr isEqualToString:cardMarkString])
        {
            chargeMoneyView.cardNumLable.text = [NSString stringWithFormat:@"尾号 %@ %@",[self.selectedBankCardInfo.bankCardNum substringFromIndex:[self.selectedBankCardInfo.bankCardNum length] - 4],bankCardTypeStr];;
            NSLog(@"chargeMoneyView.cardNumLable.text = == %@",chargeMoneyView.cardNumLable.text);
            chargeMoneyView.cardlogoImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"a%@.png",cardMarkString]];
            break;
        }
    }
}
- (void)sendBankCardInfo:(PABankCardInfo *)getCardInfo
{
    cardMarkArray = [BANKCARD_MARK componentsSeparatedByString:@","]; //本地银行名字（简写）
    getBankCardID = getCardInfo.bankCardId;  //银行卡id  （卡的唯一标识）
    cardMarkStr = getCardInfo.bankMark;      //对应某个银行的名字简写
    
    if (getCardInfo.bankCardType == BCT_DEBIT_CARD)
    {
        bankCardTypeStr = @"信用卡";
    }
    
    if (getCardInfo.bankCardType == BCT_CREDIT_CARD)
    {
        bankCardTypeStr = @"借记卡";
    }
    
    NSLog(@"====== %@ \n ====%@ ",getCardInfo.bankCardNum,bankCardTypeStr);

    for (int i = 0; i < [cardMarkArray count]; i++)
    {
        NSString * cardMarkString = [cardMarkArray objectAtIndex:i];
        if ([cardMarkStr isEqualToString:cardMarkString])
        {
            if ([chargeMoneyView.cardNumLable.text length]>0)
            {
                chargeMoneyView.cardNumLable.text = @"";
                chargeMoneyView.cardlogoImage.image = [UIImage imageNamed:@""];
            }
            chargeMoneyView.cardNumLable.text = [NSString stringWithFormat:@"尾号 %@ %@",[getCardInfo.bankCardNum substringFromIndex:[getCardInfo.bankCardNum length] - 4],bankCardTypeStr];;
            NSLog(@"chargeMoneyView.cardNumLable.text = == %@",chargeMoneyView.cardNumLable.text);
            chargeMoneyView.cardlogoImage.image = [UIImage imageNamed:[NSString stringWithFormat:@"a%@.png",cardMarkString]];
            break;
        }
    }
}
- (void)viewDidLoad
{
    [super viewDidLoad];
}
- (void)selectedBankCard:(NSNotification *)notif
{
    PABankCardInfo *selectedBankCardInfo = [notif object];
    self.selectedBankCardInfo = selectedBankCardInfo;
}
#pragma mark -
#pragma mark ========================================
#pragma mark UIAlertViewDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == 10 && buttonIndex == 0)
    {
        for (PABaseViewController *controller in self.navigationController.viewControllers)
        {
            if ([controller isKindOfClass:[PAPersonalViewController class]])
            {
                [self.navigationController popToViewController:controller animated:YES];
            }
        }
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [self.navigationController setNavigationBarHidden:YES animated:NO];
    
    chargeMoneyView.confirmButton.enabled = NO;
    [chargeMoneyView.confirmButton setBackgroundImage:[UIImage imageNamed:@"button_B1.png"] forState:UIControlStateNormal];
    chargeMoneyView.confirmButton.titleLabel.textColor = ENABLE_COLOR;

    chargeMoneyView.payMoneyImage.image = [UIImage imageNamed:@"textbox.png"];
    chargeMoneyView.payPassImage.image = [UIImage imageNamed:@"textbox.png"];

    chargeMoneyView.moneyText.text = @"";
    chargeMoneyView.payPwdText.text = @"";
    //chargeMoneyView.moneyText.delegate = self;
    [chargeMoneyView.moneyText resignFirstResponder];
    [chargeMoneyView.payPwdText addTarget:self action:@selector(changeCheckButtonState:) forControlEvents:UIControlEventEditingChanged];
}

- (void)pushAddCardView:(id)sender
{
    if ([[PAStateType sharedInstance].personalOrCharge isEqualToString:@"20"]) {
        [self.navigationController pushViewController:controllerT animated:YES];
    }
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self loadSelecteBankCardInfo];
}
- (void)changeCheckButtonState:(UITextField *)getUserNameTF
{
    if ([chargeMoneyView.payPwdText.text length] > 0 && [chargeMoneyView.moneyText.text length] > 0)
    {
        chargeMoneyView.confirmButton.enabled = YES;
        [chargeMoneyView.confirmButton setBackgroundImage:[UIImage imageNamed:@"button_A1.png"] forState:UIControlStateNormal];
        [chargeMoneyView.confirmButton setBackgroundImage:[UIImage imageNamed:@"button_A2.png"] forState:UIControlStateHighlighted];
        [chargeMoneyView.confirmButton setTitleColor:ABLE_COLOR forState:UIControlStateNormal];
        [chargeMoneyView.confirmButton setTitleColor:ABLE_COLOR forState:UIControlStateHighlighted];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

@end
